<?php

/**
 * Desc: 登录注册控制器
 * Created by lwx
 * Date: 2018-08-14
 */

namespace App\Http\WechatAuth\Controllers;

use App\Api\BaseClass\Controller;
use App\Core\Facades\User as UserFacades;
use App\Http\WechatAuth\Classes\ShortMessage;
use App\Http\WechatAuth\Models\User;
use App\Http\WechatAuth\Models\MobileCode;
use App\Http\WechatAuth\Models\TeamMember;
use App\Http\WechatAuth\Models\UserIntegralLog;
use App\Http\WechatAuth\Models\UserCashRequestLog;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
// use App\Core\Contracts\UserContract;


class RegisterController extends Controller
{

    public function __construct()
    {


        parent::__construct();
    }

    /**
     * 用户注册
     */
    public function register()
    {
        $rules = [
            ['user_name', 'required|string'],
            ['mobile', 'required|integer'],
            ['id_card_no', 'required|integer'],
            ['code', 'required|integer'],
            ['recommend_code', 'required|integer'],
            ['password', 'required|string'],
            ['address', 'string'],
            ['card_no', 'integer']
        ];
        $params = $this->form->camelFormOrFail($rules);
        $params['password'] = Crypt::encryptString($params['password']);
        $same_mobile_user = User::Where('mobile', $params['mobile'])->first();
        $code = MobileCode::where('mobile', $params['mobile'])->first();
        if (!isset($code) || $code['code'] !== $params['code']) {
            return $this->form->error('验证码错误，请重试！');
        }
        $max_diff_minute = 3;
        $diff_minutes = Carbon::now()->diffInMinutes($code['updated_at']);
        if ($max_diff_minute <= $diff_minutes) {
            return $this->form->error('验证码已过期');
        }
        if (!empty($same_mobile_user)) {
            return $this->form->error('手机号已存在');
        }
        $same_name_user = User::Where('user_name', $params['user_name'])->first();
        unset($params['code']);
        $params['is_active'] = 0;
        $res = User::create($params);
        if ($res) {
            return $this->form->success('注册成功');
        } else {
            return $this->form->error('注册失败');
        }
    }

    /**
     * 手机号绑定第一步，发送验证码
     */
    public function sendMobileCode()
    {
        $rules = [
            ['a', 'required|string']
        ];
        $params = $this->form->camelFormOrFail($rules);

        // 判断是否存在验证码
        $mobile_code = MobileCode::where('mobile', $params['a'])->first();
        $user = User::where('mobile', $params['a'])->first();
        if (isset($user)) {
            return $this->form->error('该手机号已注册！');
        }
        // 如果存在判断是否在60秒内发送的
        if (isset($mobile_code)) {

            // 当前时间
            $now = Carbon::now();

            // 最后有效时间
            $lost_time = $mobile_code->created_at->addSeconds(60);

            // 如果还没有失效，就不能发送验证码
            if ($lost_time->gt($now) === true) {
                return $this->form->error('60秒内不能重复发送验证码～');
            }


        } else {
            $mobile_code = new MobileCode();
        }

        // 生成新的验证码
        $code = '';
        for ($i = 0; $i < 6; $i++) {
            $code .= random_int(0, 9);
        }

        // 更新|添加验证码记录
        $mobile_code->fill([
            'mobile' => $params['a'],
            'code' => $code
        ])->save();

        // 发送验证码

        with(new ShortMessage)->singleSend($mobile_code->mobile, "【江西安纳斯】您的验证码是$mobile_code->code");
        return $this->form->success($code);
    }

    /**
     * 手机号绑定第二步，确认验证码
     */
    public function confirmMobileCode(AuthContract $auth)
    {
        $params = $this->form->checkParams(['mobile:min:11|max:11', 'code:min:6|max:6s']);

        // 判断验证码手机号是否匹配
        $mobile_code = MobileCode::where($params)->first();

        if (!isset($mobile_code)) {
            return $this->form->error('验证码与手机号不匹配～');
        };

        // 把手机号加入到用户信息中
        $auth->user->mobile = $params['mobile'];
        $auth->user->save();

        return $this->form->success('绑定成功～');
    }

    /**
     * 获取所属推荐码人的姓名电话
     */
    public function info()
    {
        $rules = [
            ['recommend_code', 'required|string'],
        ];
        $params = $this->form->camelFormOrFail($rules);
        $info = User::where('my_recommend_code', $params['recommend_code'])->first();
        if (!isset($info['my_recommend_code'])) {
            return $this->form->error('推荐码输入错误！');
        }
        $userinfo['user_name'] = $info->user_name;
        $userinfo['mobile'] = $info->mobile;
        return $this->form->datas($userinfo);
    }

    /**
     * 获取个人信息
     */
    public function userInfoGet()
    {
        // $user_model = UserFacades::user();
        return $this->form->getMessage(User::where('id', UserFacades::user()->id)->first());
    }

    /**
     * 编辑个人信息
     */
    public function userInfoUpdate()
    {
        $rules = [
            ['card_no', 'integer'],
            ['address', 'string']
        ];
        $params = $this->form->camelFormOrFail($rules);
        return $this->form->updateMessage(User::where('id', UserFacades::user()->id)->update($params));
    }

    /**
     * 发起提现
     */
    public function putForward()
    {
        $rules = [
            ['changed_integral', 'required|integer'],
            ['card_no', 'required|integer'],
            ['bank_name', 'required|string'],
            ['user_name', 'required|string'],
            ['mobile', 'required|integer']
        ];
        $params = $this->form->camelFormOrFail($rules);
        DB::beginTransaction();
        try {
            if ($params['changed_integral'] <= 0 || $params['changed_integral'] % 500 !== 0) {
                return $this->form->error('提现必须是500的倍数，请重试！！！');
            }
            $user_model = UserFacades::user();
            $user_model->decrement('integral', $params['changed_integral']);
            if ($user_model->integral < 0) {
                throw new \Exception("余额不足，无法提现！");
            }
            // 插入提现申请表
            $insert = [
                'uid' => $user_model->id,
                'user_name' => $params['user_name'],
                'mobile' => $params['mobile'],
                'changed_integral' => $params['changed_integral'],
                'card_no' => $params['card_no'],
                'bank_name' => $params['bank_name'],
                'status' => 0,
            ];
            $cash = UserCashRequestLog::create($insert);
            // 插入积分表
            $create = [
                'uid' => $user_model->id,
                'changed_integral' => $params['changed_integral'],
                'current_integral' => $user_model->integral,
                'type' => 0,
                'is_finished' => 0,
                'desc' => '账户提现',
                'cash_log_id' => $cash->id,
            ];
            UserIntegralLog::create($create);
        } catch (\Exception $e) {
            DB::rollback();
            return $this->form->error($e->getMessage());
        }
        DB::commit();
        return $this->form->success('提现申请成功，请耐心等待审核！');
    }

    /**
     * 积分明细列表
     */
    public function listForward()
    {
        $rules = [
            ['offset', 'required|integer'],
            ['limit', 'required|integer']
        ];
        $params = $this->form->camelFormOrFail($rules);
        $search_params = [
            ['orderBy', 'created_at', 'desc'],
            ['where', 'uid', UserFacades::user()->id],
        ];
        $userintegrallog = (new UserIntegralLog)->pagination($params, $search_params);
        return $this->form->getMessage($userintegrallog);

    }

    /**
     * 用户修改密码
     */
    public function passwordUpdate()
    {
        $rules = [
            ['password', 'required|string'],
            ['new_password', 'required|string'],
            ['confirm_password', 'required|string']
        ];
        $params = $this->form->camelFormOrFail($rules);
        $user_model = UserFacades::user();
        $user = User::where('id', $user_model->id)->first();
        // 判断原密码是否正确
        if (Crypt::decryptString($user->password) != $params['password']) {
            return $this->form->error('原密码错误');
        }
        // 判断两次密码是否一致
        if ($params['new_password'] !== $params['confirm_password']) {
            return $this->form->error("两次输入的密码不一致");
        }
        // 加密新密码
        $user->password = Crypt::encryptString($params['new_password']);
        $user->save();
        // $update = User::where('id', $user->id)->update(['password' => $params['new_password']]);
        // if (empty($update)) {
        //     return self::error('更新失败，请重试');
        // }
        return $this->form->updateMessage($user);
    }

    /**
     * 获取直属下级成员
     */
    public function teamMember()
    {
        $rules = [
            ['offset', 'required|integer'],
            ['limit', 'required|integer']
        ];
        $params = $this->form->camelFormOrFail($rules);
        $search_params = [
            ['orderBy', 'created_at', 'desc']
        ];
        $user = UserFacades::user();
        $team = TeamMember::where('uid', $user->id)->get(['sub_uid']);
        $data['user_name'] = TeamMember::where('sub_uid',$user->id)->first();
        if(!empty($data['user_name'])){
            $data['user_name'] = User::where('id',$data['user_name']->uid)->first()->user_name;
        }else{
            $data['user_name'] = '';
        }
        $data['team'] = User::whereIn('id', $team)
        ->offset($params['offset'])
        ->limit($params['limit'])
        ->get();
        foreach($data['team'] as $val) {
            $val['team'] = TeamMember::where('uid', $val->id)->get(['sub_uid']);
            $this->all += $val['team']->count();
            $this->all($val['team']);
            $val['all'] = $this->all;
            $this->all = 0;
            unset($val['team']);
        }
        $message['total'] = User::whereIn('id', $team)->count();
        $message['rows'] = $data;
        return $this->form->getMessage($message);
    }
    private $all = 0;
    public function all($array)
    {
        if (!empty($array)) {
            foreach ($array as $val) {
                $team = TeamMember::where('uid', $val->sub_uid)->get(['sub_uid']);
                $this->all += count($team);
                $this->all($team);
            }
        }
    }



}